package io.renren.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.Update;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.modules.module.entity.Module;
import io.renren.modules.module.service.ModuleServicex;
import io.renren.modules.product.entity.ProductEntity;
import io.renren.modules.product.entity.ProductUserEntity;
import io.renren.modules.product.mapper.ProductMapper;
import io.renren.modules.product.service.ProductService;
import io.renren.modules.product.service.ProductUserService;
import io.renren.modules.product.vo.ProductCeateVo;
import io.renren.modules.product.vo.ProductUpdateVo;
import io.renren.modules.product.vo.ProductVo;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.test.library.entity.Library;
import io.renren.modules.test.library.service.LibraryService;
import io.renren.modules.test.usecase.service.CaseLibraryService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhaoyu
 * @since 2023-07-29
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductEntity> implements ProductService {
    @Autowired
    SysUserService userService;
    @Autowired
    ProductUserService productUserService;
    @Autowired
    @Lazy(value = true)
    ModuleServicex moduleServicex;
    @Autowired
    @Lazy(value = true)
    LibraryService libraryService;

    @Override
    public Page<ProductVo> getList(Integer current, Integer pageSize, String productName, Long memberId) {
        //获取该用户加入的产品id
        List<ProductUserEntity> productUserEntityList = productUserService
                .list(new LambdaQueryWrapper<ProductUserEntity>()
                .eq(ProductUserEntity::getUserId, memberId));
        //当前访问的用户所在的产品id
        List<Long> productIds = productUserEntityList.stream().map(productUserEntity -> productUserEntity.getProductId())
                .collect(Collectors.toList());
        //开始分页
        Page<ProductVo> page = new Page<>();
        Page<ProductEntity> productPage = this.page(
                new Page<>(current, pageSize),
                new LambdaQueryWrapper<ProductEntity>()
                        .likeRight(StringUtils.isNotBlank(productName),
                                ProductEntity::getProductName,
                                productName));
        List<ProductEntity> productList = productPage.getRecords();
        List<ProductVo> productVoList = productList.stream().map(product -> {
            ProductVo productVo = new ProductVo();
            Long userId = product.getCreateUser();
            SysUserEntity user = userService.getById(userId);
            BeanUtils.copyProperties(product, productVo);
            productVo.setUsername(user.getUsername());
            productVo.setUpdateTime(product.getLastEditTime());
            return productVo;
        }).filter(productVo -> productIds.contains(productVo.getProductId())).collect(Collectors.toList());
        BeanUtils.copyProperties(productPage, page);
        page.setRecords(productVoList);
        page.setSize(productVoList.size());
        return page;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void createProduct(ProductCeateVo productCeateVo) {

        //获取当前创建产品的用户id
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        Long userId = principal.getUserId();
        //保存产品信息
        ProductEntity product = new ProductEntity();
        BeanUtils.copyProperties(productCeateVo,product);
        product.setCreateUser(userId);
        this.save(product);
        //保存产品成员
        productUserService.updateProductUser(product.getProductId(),productCeateVo.getMemberIds());
        //添加管理员到产品团队
        ProductUserEntity admin = new ProductUserEntity();
        admin.setProductId(product.getProductId());
        admin.setUserId(1L);
        productUserService.save(admin);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteProductById(Long id) {
        baseMapper.update(new ProductEntity(),new LambdaUpdateWrapper<ProductEntity>()
                .eq(ProductEntity::getProductId,id)
                .set(ProductEntity::getDelStatus,2));
        // 删除产品下成员
        productUserService.update(new ProductUserEntity(),new LambdaUpdateWrapper<ProductUserEntity>()
                .eq(ProductUserEntity::getProductId,id)
                .set(ProductUserEntity::getDelStatus,2));

        //删除产品下模块
        List<Module> modules = moduleServicex.list(new LambdaQueryWrapper<Module>()
                .eq(Module::getProductId, id));
        for (Module module : modules) {
            Long moduleId = module.getModuleId();
            moduleServicex.deleteModule(moduleId);
        }
        //删除产品下测试库（测试库删除测试用例）
        libraryService.list(new LambdaQueryWrapper<Library>()
                .eq(Library::getProductId,id)).stream().forEach(library -> {
            Long libraryId = library.getLibraryId();
            libraryService.removeLibrary(libraryId);
        });


    }

    @Override
    public void updateProductById(ProductUpdateVo productUpdateVo) {
        ProductEntity product = new ProductEntity();
        BeanUtils.copyProperties(productUpdateVo,product);
        this.updateById(product);
    }


}
